#include "SequentialStack.h"

SequentialStack *init_stack() {
    SequentialStack *stack = (SequentialStack *)malloc(sizeof(SequentialStack));
    stack->top = -1;
    return stack;
}

int is_empty(SequentialStack *stack) {
    return stack == NULL || stack->top == -1;
}

ElemType top(SequentialStack *stack) {
    if (is_empty(stack)) {
        printf("top: empty stack.\n");
        return -1;
    }
    return stack->data[stack->top];
}

void push(SequentialStack *stack, ElemType data) {
    if (stack->top == -1) {
        stack->size = STACK_INIT_SIZE;
        stack->data = (ElemType *)malloc(sizeof(ElemType) * stack->size);
    } else if (stack->top == STACK_INIT_SIZE - 1) {
        stack->size += stack->size >> 1;
        stack->data =
            (ElemType *)realloc(stack->data, sizeof(ElemType) * stack->size);
    }
    stack->data[++stack->top] = data;
}

ElemType pop(SequentialStack *stack) {
    if (is_empty(stack)) {
        printf("pop: empty stack.\n");
        return -1;
    }
    return stack->data[stack->top--];
}

int size(SequentialStack *stack) { return stack->top + 1; }

void clear_stack(SequentialStack *stack) {
    if (stack) {
        // stack->top = -1;
        // 释放数据域
        free(stack->data);
        // 释放栈本身
        free(stack);
    }
}

void pop_all(SequentialStack *stack) {
    printf("[TOP >> ");
    while (!is_empty(stack)) {
        printf("%d >> ", pop(stack));
    }
    printf("BOTTOM]\n");
}